﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Dycox.ComponentModel;

namespace Dycox.Data
{
    public class ModelFactory
    {
        public static void Replicate<T>(T src, T dest)
            where T : class
        {
            if (src == null) throw new ArgumentNullException("src");
            if (dest == null) throw new ArgumentNullException("dest");

            Type type = typeof(T);

            foreach (PropertyInfo p in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
            {
                ModelPropertyAttribute ska = (ModelPropertyAttribute)Attribute.GetCustomAttribute(p, typeof(ModelPropertyAttribute));

                if (ska != null && (ska.Usage == ModelPropertyUsage.User || ska.Usage == ModelPropertyUsage.Application) && ska.CanModify)
                {
                    object value = p.GetValue(src, null);

                    if (value is ICloneable)
                        value = ((ICloneable)value).Clone();

                    p.SetValue(dest, value, null);
                }
            }
        }
    }
}
